package com.leyou.page.service;

import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exception.LyException;
import com.leyou.item.client.ItemClient;
import com.leyou.item.dto.BrandDTO;
import com.leyou.item.dto.CategoryDTO;
import com.leyou.item.dto.SpecGroupDTO;
import com.leyou.item.dto.SpuDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.thymeleaf.context.Context;
import org.thymeleaf.spring5.SpringTemplateEngine;

import java.io.File;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class PageService {

    @Autowired
    private ItemClient itemClient;

    // 模板引擎
    @Autowired
    private SpringTemplateEngine templateEngine;

    // 静态页面存放的位置
    @Value("${ly.static.itemDir}")
    private String itemDir;

    // 模板的名称，省略.html
    @Value("${ly.static.itemTemplate}")
    private String itemTemplate;



    /**
     * 加载数据
     * @param id
     * @return
     */
    public Map<String, Object> loadItemData(Long id) {
        // 查询spu
        SpuDTO spu = itemClient.querySpuById(id);
        // 查询分类
        List<CategoryDTO> categoryDTOList = itemClient.queryCategoryByIds(spu.getCategoryIds());
        // 查询品牌
        BrandDTO brandDTO = itemClient.queryBrandById(spu.getBrandId());
        // 规格参数组及组内参数
        List<SpecGroupDTO> specGroupDTO = itemClient.querySpecGroupByCId(spu.getCid3());

        // 创建
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("spuName", spu.getName());  //  spu名称
        dataMap.put("subTitle", spu.getSubTitle());  //  副标题
        dataMap.put("detail", spu.getSpuDetail());  //  详情
        dataMap.put("skus", spu.getSkus());  // sku集合
        dataMap.put("categories", categoryDTOList);  //  分类的集合
        dataMap.put("brand", brandDTO);  // 品牌
        dataMap.put("specs", specGroupDTO);  // 规格参数组及组内参数
        // 返回
        return dataMap;
    }


    /**
     * 生成静态化页面
     * @param id
     */
    public void createItemHtml(Long id){

        // 准备上下文对象
        Context context = new Context();
        context.setVariables(loadItemData(id));

        // 判断目录
        File dir = new File(itemDir);
        if(!dir.exists()){
            boolean mkdir = dir.mkdir();
            if(!mkdir){
                throw new LyException(ExceptionEnum.DIRECTORY_WRITER_ERROR);
            }
        }

        // 准备writer
        File file = new File(dir, id + ".html");

        // 做合法校验
        try(PrintWriter writer = new PrintWriter(file, "UTF-8");){
            templateEngine.process(itemTemplate,context, writer);
        }catch (Exception e){
            throw new LyException(ExceptionEnum.FILE_WRITER_ERROR);
        }
    }

    /**
     * 删除静态页面
     * @param id
     */
    public void deleteItemHtml(Long id) {
        File file = new File(itemDir, id + ".html");
        boolean delete = file.delete();
        if(!delete){
            throw new LyException(ExceptionEnum.DELETE_OPERATION_FAIL);
        }
    }
}
